package com.siecom.update;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.concurrent.CountDownLatch;

public class UpdateActivity extends AppCompatActivity {

    private static final String TAG = UpdateActivity.class.getSimpleName();
    private String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        path = getIntent().getStringExtra("path");
        Log.e(TAG,"inPath == " + path);
        if (TextUtils.isEmpty(path)) {
            path = "/sdcard/host.apk";
            finish();
            return;
        }
        updateApkSlience(path);
        Log.e(TAG,"path == " + path);
    }

    public void updateApkSlience(String name) {
        PackageManager mPm = getApplicationContext().getPackageManager();

        boolean isSuc = installApp(name);
        if (isSuc) {

            ComponentName componetName = new ComponentName(
                    "com.siecom.hostservice", //这个是另外一个应用程序的包名
                    "com.siecom.hostservice.MainActivity"); //这个参数是要启动的Activity的全路径名

            try {

                Intent intent = new Intent();

                intent.setComponent(componetName);

                startActivity(intent);
                Toast.makeText(this, "升级成功", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {

                Toast.makeText(this, "跳转异常，请检查跳转配置、包名及Activity访问权限", Toast.LENGTH_SHORT).show();

            }
        }
        finish();

    }


    public static boolean installApp(String apkPath) {
        CountDownLatch latch = new CountDownLatch(1);
        StringBuilder successMsg = new StringBuilder();
        StringBuilder errorMsg = new StringBuilder();

        new Thread(new Runnable() {
            @Override
            public void run() {
                Process process = null;
                BufferedReader successResult = null;
                BufferedReader errorResult = null;
                try {
                    process = new ProcessBuilder("pm", "install","-i","com.siecom.update", "-r -d", apkPath).start();
                    successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
                    errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                    String s;
                    while ((s = successResult.readLine()) != null) {
                        successMsg.append(s);
                    }
                    while ((s = errorResult.readLine()) != null) {
                        errorMsg.append(s);
                    }
                } catch (Exception e) {

                } finally {
                    try {
                        if (successResult != null) {
                            successResult.close();
                        }
                        if (errorResult != null) {
                            errorResult.close();
                        }
                    } catch (Exception e) {

                    }
                    if (process != null) {
                        process.destroy();
                    }

                    latch.countDown();
                }
            }
        }).start();

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.e(TAG,"error message == "+errorMsg.toString());
        Log.e(TAG,"success message == "+successMsg.toString());
        //如果含有“success”单词则认为安装成功
        return successMsg.toString().equalsIgnoreCase("success");
    }



}